﻿using System;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework;
using DotNetNuke.Services.Localization;

namespace HeroldIT.Dnn.Modules
{
    /// <summary>
    /// Provides base functionality for ML modules.
    /// </summary>
    public class MLPortalModuleBase : PortalModuleBase
    {
        #region constants

        private static readonly object EventModuleLocalized = new object();

        #endregion

        #region events

        /// <summary>
        /// Fires after the module has been localized.
        /// </summary>
        public event EventHandler ModuleLocalized
        {
            add { this.Events.AddHandler(EventModuleLocalized, value); }
            remove { this.Events.RemoveHandler(EventModuleLocalized, value); }
        }

        /// <summary>
        /// Raises the <see cref="ModuleLocalized"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected virtual void OnModuleLocalized(EventArgs e)
        {
            EventHandler handler = (EventHandler) this.Events[EventModuleLocalized];
            if (handler != null) handler(this, e);
        }

        #endregion

        #region page lifecycle

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            Localizer.LocalizeModule(this.ModuleConfiguration, ((PageBase) this.Page).PageCulture.Name);
            this.OnModuleLocalized(EventArgs.Empty);

            base.OnInit(e);
        }

        #endregion

        #region methods

        /// <summary>
        /// Gets the localized string for the given key.
        /// </summary>
        /// <param name="key">The key for which to find the localized string.</param>
        /// <returns>The localized string for the given key.</returns>
        protected string GetString(string key)
        {
            return Localization.GetString(key, this.LocalResourceFile);
        }

        #endregion
    }
}